package com.example.zhaoping.controller;

import com.example.zhaoping.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class UploadFileController {
    /** 头像文件大小的上限值(5MB) */
    public static final int AVATAR_MAX_SIZE = 5 * 1024 * 1024;
    /** 允许上传的头像的文件类型 */
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();

    @Autowired
    private Result result;

    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/gif");
    }

    /**
     * 头像图片保存路径
     */
    @Value("${pathPatterns}")
    private String pathPatterns = "";

    @PostMapping(value = "/upload",name = "上传文件")
    public Result<?> UploadFile(@RequestParam MultipartFile file) throws Exception {
        if(file.isEmpty()){
            return result.error("上传的头像文件不允许为空");
        }
        if(file.getSize() > AVATAR_MAX_SIZE){
            return result.error("上传的图片不允许超过"+ (AVATAR_MAX_SIZE/1024) +"kb");
        }
        // 判断上传文件的类型
        if(!AVATAR_TYPES.contains(file.getContentType())){
            return result.error("不支持使用该类型的文件作为头像，\n允许的文件类型：" + AVATAR_TYPES);
        }
        // 判断保存头像图片的目录是否存在，不存在则创建
        File dir = new File(pathPatterns.replace("file:",""));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //头像文件名
        String portrait = "";
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        int beginIndex = originalFilename.lastIndexOf(".");
        if(beginIndex > 0){portrait = originalFilename.substring(beginIndex);}

        String filename = UUID.randomUUID().toString() + portrait;
        File dest = new File(dir,filename);
//        System.out.println(dest);
        try{
            //保存图片
            file.transferTo(dest);
        }catch (IllegalStateException e){
            return result.error("文件状态异常，可能文件已被移动或删除！");
        }catch (IOException e){
            return result.error("上传文件时读写错误，请稍后重新尝试！");
        }
        return result.success("上传成功！","/upload/image/"+filename);
    }

    @PostMapping(value = "/register/upload",name = "注册上传图片")
    public Result RegisterUploadFile(@RequestParam MultipartFile file) throws Exception {
        return UploadFile(file);
    }
    /*
    批量上传
     */
    @PostMapping(value="/uploads",name = "批量上传文件")
    public Result<?> Uploads(){
        return new Result<>(200,"上传成功！",null);
    }

    @PostMapping("/updataflie")
    public Result<?> UpdataFlie(@RequestParam MultipartFile file) throws Exception{
        return new Result<>(200,"上传成功！",null);
    }
}
